﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VehicleManagement.Models;
using VehicleManagement.Codes;
using VehicleManagement.ControllersServices;
using System.IO;

namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "管理员,申请人")]
    public class ApplicantController : Controller
    {
        const int PAGE_MAX = 5;
        //
        // GET: /Applicant/

        public ViewResult Index()
        {
            IEnumerable<Applicant> lstModel = GetApplicantAs();
            return View(lstModel);
        }

        private IList<Applicant> GetApplicantAs()
        {
            string name = Request.Params["Name"];
            string telephone = Request.Params["Telephone"];
            string sex = Request.Params["Sex"];
            string nameForSearch = "%%";
            string telephoneForSearch = "%%";
            string sexForSearch = "%%";
            ApplicantService applicantService = new ApplicantService();

            if (!string.IsNullOrEmpty(name) && name != "姓名")
                nameForSearch = string.Format("%{0}%", name);
            if (!string.IsNullOrEmpty(telephone) && telephone != "电话")
                telephoneForSearch = string.Format("%{0}%", telephone);
            if (!string.IsNullOrEmpty(sex) && sex != "性别")
                sexForSearch = string.Format("%{0}%", sex);
            int page = 1;
            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
                page = int.Parse(Request.Params["Page"]);
            else
                page = 1;

            IList<Applicant> lstModel = applicantService.SearchAllApplicants(nameForSearch, 
                telephoneForSearch, sexForSearch, (page - 1) * PAGE_MAX, PAGE_MAX);
            return lstModel;
        }

        

        /// <summary>
        /// 获取申请人信息
        /// </summary>
        /// <param name="id">申请人ID</param>
        /// <returns></returns>
        public ActionResult GetApplicantInfo(int id)
        {
            ApplicantService applicantService = new ApplicantService();
            IList<Applicant> lstModel = applicantService.GetAllApplicants();
            Applicant applicantInfo = lstModel.Where(u => u.ApplicantID == id).First();
            return View(applicantInfo);
        }

        //
        // GET: /Applicant/Details/5

        public ViewResult Details(int id)
        {
            ApplicantService applicantService = new ApplicantService();
            IList<Applicant> lstModel = applicantService.GetAllApplicants();
            Applicant applicant = lstModel.Where(u => u.ApplicantID == id).First();
            return View(applicant);
        }

        //
        // GET: /Applicant/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Applicant/Create

        [HttpPost]
        public ActionResult Create(Applicant applicant)
        {
            if (ModelState.IsValid)
            {
                ApplicantService applicantService = new ApplicantService();
                Object thisLock = new Object();
                int id = 0;
                lock (thisLock)
                {
                    // Critical code section
                    applicantService.InsertApplicant(applicant);
                    id = (int)SqlMapperManager.Instance.Get().QueryForObject("SELECT_APPLICANT_IDENTITY", null);
                }
                HttpPostedFileBase file = Request.Files["file"];
                if (file != null)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/Applicant") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_APPLICANT_HEAD_IMAGE",
                        new
                        {
                            ApplicantID = id,
                            Image = id + fileExt
                        });
                }
                return RedirectToAction("Index");  
            }
            return View(applicant);
        }

        
        //
        // GET: /Applicant/Edit/5
 
        public ActionResult Edit(int id)
        {
            //Applicant applicant = db.Applicant.Find(id);
            ApplicantService applicantService = new ApplicantService();
            IList<Applicant> lstModel = applicantService.GetAllApplicants();
            Applicant applicant = lstModel.Where(u => u.ApplicantID == id).First();
            return View(applicant);
        }

        //
        // POST: /Applicant/Edit/5

        [HttpPost]
        public ActionResult Edit(Applicant applicant)
        {
            if (ModelState.IsValid)
            {
                ApplicantService applicantService = new ApplicantService();
                applicantService.UpdateApplicant(applicant);
                return RedirectToAction("Index");
            }
            return View(applicant);
        }

        
        //
        // GET: /Applicant/Delete/5
 
        public ActionResult Delete(int id)
        {
            ApplicantService applicantService = new ApplicantService();
            IList<Applicant> lstModel = applicantService.GetAllApplicants();
            Applicant applicant = lstModel.Where(u => u.ApplicantID == id).First();
            return View(applicant);
        }

        //
        // POST: /Applicant/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            ApplicantService applicantService = new ApplicantService();
            try
            {
                applicantService.DeleteApplicant(id);
                return Json(new { Result = "true", Message = "删除成功" });
            }
            catch(Exception ex)
            {
                return Json(new { Result = "false", Message = ex.Message });
            }
        }

        [HttpPost, ActionName("UploadHeadImage")]
        public ActionResult UploadHeadImage()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null)
            {
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                file.SaveAs(Server.MapPath("~/Photos/Applicant") + @"\" + Request.Form["ApplicantID"] + fileExt);
                try
                {
                    SqlMapperManager.Instance.Get().Update("UPDATE_APPLICANT_HEAD_IMAGE",
                        new
                        {
                            ApplicantID = Request.Form["ApplicantID"],
                            Image = Request.Form["ApplicantID"] + fileExt
                        });
                    //return Json(new { Result = "true", Message = "头像更新成功" });
                    return Redirect("Edit/" + Request.Form["ApplicantID"]);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "false", Message = ex.Message });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "头像更新失败" });
            }
        }

        [HttpGet, ActionName("GetPagingInfo")]
        public ActionResult GetPagingInfo()
        {
            ApplicantService applicantService = new ApplicantService();
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);
            string name = Request.Params["Name"];
            string telephone = Request.Params["Telephone"];
            string sex = Request.Params["Sex"];
            string nameForSearch = "%%";
            string telephoneForSearch = "%%";
            string sexForSearch = "%%";

            if (!string.IsNullOrEmpty(name) && name != "姓名")
                nameForSearch = string.Format("%{0}%", name);
            if (!string.IsNullOrEmpty(telephone) && telephone != "电话")
                telephoneForSearch = string.Format("%{0}%", telephone);
            if (!string.IsNullOrEmpty(sex) && sex != "性别")
                sexForSearch = string.Format("%{0}%", sex);

            int itemCount = applicantService.GetApplicantCount(nameForSearch, telephoneForSearch, sexForSearch);
            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            }, JsonRequestBehavior.AllowGet);
        }

        //[HttpPost,HttpGet,ActionName("Search")]
        //public ViewResult Search()
        //{
        //    string name = Request.Form["Name"];
        //    string telephone = Request.Form["Telephone"];
        //    string sex = Request.Form["Sex"];
        //    ApplicantService applicantService = new ApplicantService();
        //    IList<Applicant> applicantList = applicantService.GetAllApplicants();
            
        //    return View(applicantList.Where(item => item.Name.Contains(name) && item.Telephone.Contains(telephone) && item.Sex == sex));
        //}
    }
}